
<template>
  <div>
    <div class="gva-form-box">  
  <el-form :model="formData" ref="elFormRef" :rules="rules" label-position="left" label-width="80px" size="large"
    @submit.native.prevent>
    <div class="card-container">
      <el-card style="{width: 100% !important}" shadow="never">
        <div slot="header" class="clear-fix">
          <span style="font-size: 30px;font-weight: bold;">故障档案录入</span>
          <i class="float-right el-icon-arrow-down"></i>
        </div>
        <el-row>
          <el-col :span="8" class="grid-cell">
            <el-form-item label="ATA章节(一级)" label-width="100px" prop="ata_chapter_level1"
              class="required label-center-align">
              <el-input v-model="formData.ata_chapter_level1" type="text" clearable placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="grid-cell">
            <el-form-item label="ATA章节(二级)" label-width="100px" prop="ata_chapter_level2"
              class="required label-center-align">
              <el-input v-model="formData.ata_chapter_level2" type="text" clearable placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="grid-cell">
            <el-form-item label="故障编号" label-width="100px" prop="fault_number"
              class="required label-center-align">
              <el-input v-model="formData.fault_number" type="text" clearable placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="故障名称" prop="fault_name" class="label-center-align">
          <el-input v-model="formData.fault_name" type="text" clearable placeholder="请输入"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="8" class="grid-cell">
            <el-form-item label="AO号" prop="ao_number" class="label-center-align">
              <el-input v-model="formData.ao_number" type="text" clearable placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="grid-cell">
            <el-form-item label="架次" prop="sorties" class="label-center-align">
              <el-input v-model="formData.sorties" type="text" clearable placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="grid-cell">
            <el-form-item label="排故时间:" prop="troubleshooting_time">
              <el-date-picker v-model="formData.troubleshooting_time" type="date" placeholder="选择日期" :clearable="true"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="grid-cell">
            <el-form-item label="图纸号" prop="drawing_number" class="label-center-align">
              <el-input v-model="formData.drawing_number" type="text" clearable placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="grid-cell">
            <el-form-item label="登记人" prop="register_person" class="label-center-align">
              <el-input v-model="formData.register_person" type="text" clearable placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" class="grid-cell">
            <el-form-item label="登记人工号" prop="register_person_number" class="label-center-align">
              <el-input v-model="formData.register_person_number" type="text" clearable placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="设计要求的操作和响应" label-width="150px"
          prop="operation_and_response_to_design_requirements" class="label-center-align">
          <el-input type="textarea" v-model="formData.operation_and_response_to_design_requirements" rows="3" placeholder="请输入">
          </el-input>
        </el-form-item>
        <el-form-item label="故障现象" prop="symptoms" class="label-center-align">
          <el-input type="textarea" v-model="formData.symptoms" rows="3" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="排故思路" prop="troubleshooting_ideas" class="label-center-align">
          <el-input type="textarea" v-model="formData.troubleshooting_ideas" rows="15" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="故障类型" prop="fault_type" class="label-center-align">
          <el-select v-model="formData.fault_type" class="full-width-input" clearable>
            <el-option v-for="(item, index) in fault_typeOptions" :key="index" :label="item.label"
              :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排故步骤" prop="troubleshooting_steps" class="label-center-align">
          <el-input type="textarea" v-model="formData.troubleshooting_steps" rows="3" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="故障定位" prop="fault_location" class="label-center-align">
          <el-input type="textarea" v-model="formData.fault_location" rows="3" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="结论录入" prop="conclusion" class="label-center-align">
          <el-input type="textarea" v-model="formData.conclusion" rows="3" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="参考资料" prop="references" class="label-center-align">
          <el-input type="textarea" v-model="formData.references" rows="3" placeholder="请输入"></el-input>
        </el-form-item>

      </el-card>
    </div>

    <div class="card-container">
    <el-card style="{width: 100% !important}" shadow="never">
      <div slot="header" class="clear-fix">
        <span style="font-size: 30px;font-weight: bold;">图片上传模块</span>
        <i class="float-right el-icon-arrow-down"></i>
      </div>
      <div v-loading.fullscreen.lock="fullscreenLoading">
        <div class="gva-table-box">
          <warning-bar
            title="附件上传"
          />
          <div class="gva-btn-list">
            <upload-image
              v-model:imageUrl="imageUrl"
              :file-size="512"
              :max-w-h="1080"
              :ateremark="search.keyword"
              class="upload-btn"
              @on-success="getTableData"
            />
    
            <!-- <el-form ref="searchForm" :inline="true" :model="search">
              <el-form-item label="">
                <el-input v-model="search.keyword" class="keyword" placeholder="请输入文件名或备注" />
              </el-form-item>
    
              <el-form-item>
                <el-button type="primary" icon="search" @click="getTableData">查询</el-button>
              </el-form-item>
            </el-form> -->
    
          </div>
    
            <el-table :data="tableData">
              <el-table-column align="left" label="预览" width="400">
                <template #default="scope">
                  <CustomPic pic-type="file" :pic-src="scope.row.url" />
                </template>
              </el-table-column>
              <el-table-column align="left" label="日期" prop="UpdatedAt" width="180">
                <template #default="scope">
                  <div>{{ formatDate(scope.row.UpdatedAt) }}</div>
                </template>
              </el-table-column>
              <!-- <el-table-column align="left" label="文件名/备注" prop="name" width="180">
                <template #default="scope">
                  <div class="name" @click="editFileNameFunc(scope.row)">{{ scope.row.name }}</div>
                </template>
              </el-table-column> -->
              <!-- <el-table-column align="left" label="链接" prop="url" min-width="300" /> -->
              <el-table-column align="left" label="标签" prop="tag" width="100">
                <template #default="scope">
                  <el-tag
                    :type="scope.row.tag === 'jpg' ? 'primary' : 'success'"
                    disable-transitions
                  >{{ scope.row.tag }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column align="left" label="操作" width="160">
                <template #default="scope">
                  <el-button icon="download" type="primary" link @click="downloadFile(scope.row)">下载</el-button>
                  <el-button icon="delete" type="primary" link @click="deleteFileFunc(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="gva-pagination">
              <el-pagination
                :current-page="page"
                :page-size="pageSize"
                :page-sizes="[3, 5, 10]"
                :style="{ float: 'right', padding: '20px' }"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
              />
            </div>
          </div>
    
          </div>

    </el-card>
    </div>

  <div class="card-container">
    <el-card style="{width: 100% !important}" shadow="never">
      <div slot="header" class="clear-fix">
        <span style="font-size: 30px;font-weight: bold;">故障树绘制模块</span>
        <i class="float-right el-icon-arrow-down"></i>
      </div>
        <Diagram ref="DiagramInstance" @DiagramData="handleDiagramData" :DiagramData="DiagramData_init" />

    </el-card>
  </div>

  
    <el-form-item style="display: flex; justify-content: center; align-items: center;">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button type="primary" @click="back">返回</el-button>
        </el-form-item>
  </el-form>
  </div>
</div>
</template>

<script>
export default {
  name: 'Fault_file_struct'
}
</script>

<script setup>
// logicflow start
import Diagram from "../logicflow/Diagram.vue"
// logicflow end
// 图片上传
import { getFileList, deleteFile, editFileName } from '@/api/fileUploadAndDownload'
import { downloadImage } from '@/utils/downloadImg'
import CustomPic from '@/components/customPic/index.vue'
import UploadImage from '@/components/upload/image.vue'
import UploadCommon from '@/components/upload/common.vue'
import { formatDate } from '@/utils/format'
import WarningBar from '@/components/warningBar/warningBar.vue'

import { ElMessageBox } from 'element-plus'


// 图片上传 end

import {
  createFault_file_struct,
  updateFault_file_struct,
  findFault_file_struct
} from '@/api/sysFaultFile'

// 自动获取字典
import { getDictFunc } from '@/utils/format'
import { useRoute, useRouter } from "vue-router"
import { ElMessage } from 'element-plus'
import { ref, reactive,onMounted } from 'vue'

 // 图片上传
 const path = ref(import.meta.env.VITE_BASE_API)

const imageUrl = ref('')
const imageCommon = ref('')

const page = ref(1)
const total = ref(0)
const pageSize = ref(3)
const search = ref({keyword:'ateateate'})
const tableData = ref([])

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {

  console.log("ate log tableData",tableData)
  const table = await getFileList({ page: page.value, pageSize: pageSize.value, ...search.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}
getTableData()

const deleteFileFunc = async(row) => {
  ElMessageBox.confirm('此操作将永久删除文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async() => {
      const res = await deleteFile(row)
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功!',
        })
        if (tableData.value.length === 1 && page.value > 1) {
          page.value--
        }
        getTableData()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
}

const downloadFile = (row) => {
  if (row.url.indexOf('http://') > -1 || row.url.indexOf('https://') > -1) {
    console.log("ate download1",row.url)
    downloadImage(row.url, row.name)
  
  } else {
  
    downloadImage(path.value + '/' + row.url, row.name)
    console.log("ate download2",path.value + '/' + row.url)
  
  }
}

/**
 * 编辑文件名或者备注
 * @param row
 * @returns {Promise<void>}
 */
const editFileNameFunc = async(row) => {
  ElMessageBox.prompt('请输入文件名或者备注', '编辑', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S/,
    inputErrorMessage: '不能为空',
    inputValue: row.name
  }).then(async({ value }) => {
    row.name = value
    console.log("ate log row picture",row)
    const res = await editFileName(row)
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '编辑成功!',
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消修改'
    })
  })
}
  // 图片end
const route = useRoute()
const router = useRouter()
const fault_typeOptions = ref([
  { label:"sdf", value:'sdf'},
  { label:"sdf",value:'sdf'}
])
const type = ref('')
const formData = ref({
            ata_chapter_level1: '',
            ata_chapter_level2: '',
            fault_number: '',
            fault_name: '',
            ao_number: '',
            sorties: '',
            troubleshooting_time: new Date(),
            drawing_number: '',
            register_person: '',
            register_person_number: '',
            operation_and_response_to_design_requirements: '',
            symptoms: '',
            troubleshooting_ideas: '',
            fault_type: '',
            troubleshooting_steps: '',
            fault_location: '',
            conclusion: '',
            references: '',
            upload_attachment: '',
            upload_fault_tree: '',
        })
// 验证规则
const rule = reactive({
               ata_chapter_level1 : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               }],
               ata_chapter_level2 : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               }],
               fault_number : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               }],
})

const elFormRef = ref()
const DiagramData_init = ref('')
// 初始化方法
const init = async () => {
 // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
    if (route.query.id) {
      const res = await findFault_file_struct({ ID: route.query.id })
      search.value['keyword'] = 'fault_file_table_'+route.query.id.toString()
      if (res.code === 0) {
        formData.value = res.data.refault_file_struct
        type.value = 'update'
      }
      
    } else {
      type.value = 'create'
    }

    getTableData()
    DiagramData_init.value = formData.value.upload_fault_tree
    console.log("ate 父组件",formData.value.upload_fault_tree)
    // DiagramInstance.value.updateDiagramData()
}

init()
// 保存按钮


const handleDiagramData = (data)=>{
  formData.value.upload_fault_tree = data

}
// DiagramInstance.value.updateDiagramData()
const DiagramInstance = ref(null)

const save = async() => {
      DiagramInstance.value.sendDiagramData()
      console.log("ate formData.value",formData.value)

      elFormRef.value?.validate( async (valid) => {
         if (!valid) return
            let res
           switch (type.value) {
             case 'create':
               res = await createFault_file_struct(formData.value)
               break
             case 'update':
               res = await updateFault_file_struct(formData.value)
               break
             default:
               res = await createFault_file_struct(formData.value)
               break
           }
           if (res.code === 0) {
             ElMessage({
               type: 'success',
               message: '创建/更改成功'
             })
           }
       })
}

// 返回按钮
const back = () => {
    router.go(-1)
}

onMounted(() => {
  // DiagramInstance.value.updateDiagramData()
})

</script>

<style lang="scss">
  .el-input-number.full-width-input,
  .el-cascader.full-width-input {
    width: 100% !important;
  }
  
  .el-form-item--medium {
    .el-radio {
      line-height: 36px !important;
    }
    
    .el-rate {
      margin-top: 8px;
    }
  }
  
  .el-form-item--small {
    .el-radio {
      line-height: 32px !important;
    }
    
    .el-rate {
      margin-top: 6px;
    }
  }
  
  .el-form-item--mini {
    .el-radio {
      line-height: 28px !important;
    }
    
    .el-rate {
      margin-top: 4px;
    }
  }
  
  .clear-fix:before,
  .clear-fix:after {
    display: table;
    content: "";
  }
  
  .clear-fix:after {
    clear: both;
  }
  
  .float-right {
    float: right;
  }
  
  .card-container {
    margin-bottom: 16px;
  }
</style>

<style lang="scss" scoped>
  div.table-container {
    table.table-layout {
      width: 100%;
      table-layout: fixed;
      border-collapse: collapse;

      td.table-cell {
        display: table-cell;
        height: 36px;
        border: 1px solid #e1e2e3;
      }
    }
  }
  
  div.tab-container {}
  
  .label-left-align ::v-deep .el-form-item__label {
    text-align: left;
  }
  
  .label-center-align ::v-deep .el-form-item__label {
    text-align: center;
  }
  
  .label-right-align ::v-deep .el-form-item__label {
    text-align: right;
  }
  
  .custom-label {}
  
  .static-content-item {
    min-height: 20px;
    display: flex;
    align-items: center;

    ::v-deep .el-divider--horizontal {
      margin: 0;
    }
  }
  
</style>